exports.main = async context => {
  const cloud = context.cloud;
  const collectionName = 'pfMkProducts';
  const products = identifyMascaraAndEyeLashes(context.data.skus);

  try {
    const collection = cloud.db.collection(collectionName);
    const deletedCount = await clear(collection);
    const insertedIds = await collection.insertMany(products);

    return {
      success: true,
      result: insertedIds
    }
  } catch (error) {
    return {
      success: false,
      error
    };
  }
};

function clear(collection) {
  return collection.deleteMany({
    _id: { $type : 'string' }
  });
}

function identifyMascaraAndEyeLashes(products = []) {
  return products.map(p =>
    p.type === 'eye_lash' ? addAttrSubType(p) : p
  );
}

function addAttrSubType(product = {}) {
  const skuHasSubType = product.items && product.items.find(sku => sku.subType);
  const isEyelashes = skuHasSubType && skuHasSubType.subType === 'eyelashes';

  return {
    ...product,
    subType: isEyelashes ? 'eyelashes' : 'mascara'
  }
}
